package com.besall.allbase.view.activity.chipstoollevel4.protocol;

import static bb.lanxing.manager.SPConstant.TIME_AUTO_SYNC;
import static bb.lanxing.manager.SPConstant.TIME_UN_AUTO_SYNC;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_SUCCESS;
import static com.bes.bessdk.BesSdkConstants.BES_GATT_DESCRIPTOR_OTA_UUID;
import static com.bes.bessdk.BesSdkConstants.BesConnectState.BES_CONNECT;
import static com.bes.bessdk.service.BesOTAConstants.BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE;
import static com.bes.sdk.message.Constants.APP_SYNC_TIME_SUCCESS;
import static com.bes.sdk.message.Constants.DEVICE_RENAME_SUCCESS;
import static com.bes.sdk.message.Constants.FIRST_GET_SETTINGS_JSON_FILE_SUCCESS;
import static com.bes.sdk.message.Constants.MANUFACTURER_HUAWEI;
import static com.bes.sdk.utils.SettingsJsonUtils.DEVICE_MODEL_DEFAULT;
import static com.bes.sdk.utils.SettingsJsonUtils.DEVICE_SN_DEFAULT;
import static com.besall.allbase.bluetooth.BluetoothConstants.Scan.BES_SCAN_RESULT;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.GET_DEVICE_SATELLITE_DATA;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.INFO_Get_mac_address;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.INFO_Set_Device_Time;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.INFO_Set_serial_number;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.INFO_Unbind_BT;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.KEY_LOCATION_FILE_ID;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.KEY_TEST_GET_LOG_FILE;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.KEY_TEST_GET_LOG_FILE_NAME;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.LOG_FILE_RESULT;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.RECEIVE_DATA_LOG;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.REQUEST_LOG_FILE;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.RETURN_SEND_LOG;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.SET_DEVICE_PKU_SUCCESS;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.SYSTEM_TRANS_ELPO_DATA_FILE;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.SYSTEM_TRANS_LOCATION_FILE;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.TEST_REQUEST_LOG_BY_FILE_NAME;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.TEST_WATCH_DIAL_OTA;
import static com.besall.allbase.common.Constants.KEY_STOP_WATCH_LOG;
import static com.besall.allbase.common.Constants.OTA_CHOOSE_FILE_PATH_RESULT;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.routebook.RouteBookDeviceActivity;
import bb.lanxing.device.sgdevcie.storage.fragment.BBWorkoutsManagerFragment;
import bb.lanxing.devices.sync.BesSportProcessor;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.api.DeviceProvider;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.AbstractXZDeviceManager;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.lib.devices.sgsettingentity.setting.Settings;
import bb.lanxing.lib.devices.sgsettingentity.workout.WorkoutState;
import bb.lanxing.lib.devices.sgsettingentity.workout.Workouts;
import bb.lanxing.lib.devices.utils.ByteUtils;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.Device;
import bb.lanxing.service.DownloadService;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.ui.AlphaLinearLayout;
import bb.lanxing.utils.IntentUtils;
import bb.lanxing.utils.TimeUtil;
import bb.lanxing.view.dialog.CircularProgressDialog;
import bb.lanxing.view.dialog.CommonDialogFragment;
import com.baidu.mapapi.model.LatLng;
import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.connect.BTService;
import com.bes.bessdk.connect.BleConnector;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BBServiceListener;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.bessdk.utils.ArrayUtil;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.message.MsgStrAnalyzer;
import com.bes.sdk.utils.DeviceProtocol;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolService;
import com.besall.allbase.common.Constants;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.common.utils.PreferenceUtil;
import com.besall.allbase.view.activity.chipstoollevel4.ota.OtaUIActivity;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings.DeviceProfilesActivity;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings.SettingsActivity;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings.StorageManagerActivity;
import com.besall.allbase.view.activity.log.StopWatchLogActivity;
import com.besall.allbase.view.base.BaseActivity;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.ToastUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ProtocolActivity extends BaseActivity<IProtocolActivity, ProtocolPresenter> implements IProtocolActivity, BesServiceListener, View.OnClickListener, CompoundButton.OnCheckedChangeListener, DialogInterface.OnCancelListener, BBServiceListener {
	private static final String TRK = "trk";
	private static final String WK = "wk";
	private final int buffSize = 8 * 1024;// add by bb
	private boolean selfColseService = false;

	private String cur_title = "Protocol";
	public AlphaLinearLayout settingsLayoutView;
	public AlphaLinearLayout firewareUpdateLayoutView;
	HmDevice mHmDevice;
	BesServiceConfig mServiceConfig;
	TextView mTextViewLog;
	// add by wangsm
	AlphaLinearLayout storageLL;
	CircularProgressDialog circularProgressDialog;
	BesSdkConstants.BesConnectState besConnectState;
	String tempData = "";
	int time = 0;
	boolean state = false;
	byte[] dataLen = new byte[2];
	byte[] totalCount = new byte[2];
	int totalCounts = 0;// 总包数
	int totalLen = 0;// 数据总长度
	byte[] mpkgData = new byte[178];
	int curLen = 0;
	int reminLen = 0;
	List<String> fileNameList = new ArrayList<>();
	// add by for auto sync
	HashMap<String, BBWorkoutsManagerFragment.WorkoutFile> workoutFileHashMap = new HashMap<>();
	Workouts mWorkouts = null;
	// test code
	BluetoothDevice btDevice = null;
	BroadcastReceiver receiver;

	private final List<String> elpoFileList = new ArrayList<String>();
	private Context mContext;
	private TextView pick_device_ble;// Button
	private TextView connect_device;// Button
	private TextView device_address;
	private TextView device_name;
	private TextView data_info;
	private AlphaLinearLayout mPanelSettingLayout;
	private AlphaLinearLayout mRoutebookSyncLayout;
	// end by wangsm
	private AlphaLinearLayout elpoLayoutView;
	private AlphaLinearLayout helpLayoutView;
	private AlphaLinearLayout fileLayoutView;
	private Animation syncAnimation;
	private ImageView syncImageView;
	private String recevieMsg = "";
	private TextView tv_satellite_expires_in;
	private String mCurrentDeviceName = "";
	private String mNewDeviceName = "";
	private boolean mOnlySyncTime = false;

	public ProtocolActivity() {
		receiver = new BroadcastReceiver() {
			@Override public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				Log.d(TAG, "the action: " + action);
				if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
					BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					if (device == null) {// || !device.equals(btDevice)
						Log.d(TAG, "the device is not bt device sent by user: ");
						return;
					}
					int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
					Log.d(TAG, "the state: " + state);
					if (state == BluetoothDevice.BOND_BONDED) {
						Log.d(TAG, "bond success: ");
					} else if (state == BluetoothDevice.BOND_BONDING) {
						Log.d(TAG, "bonding: ");
					} else if (state == BluetoothDevice.BOND_NONE) {
						Log.d(TAG, "none bond ");
					}
					String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
					Log.d(TAG, "bind name: " + name);

					String key = intent.getStringExtra(BluetoothDevice.EXTRA_PAIRING_KEY);
					Log.d(TAG, "bind key: " + key);
				} else if (Constants.ACTION_CONNECT_BLE_DEVICE.equals(action)) {
					connectBleDevice(false);
				} else if (Constants.ACTION_DISMISS_LOADING.equals(action)) {
					dismissLoading();
				}
			}
		};
	}

	@Override protected ProtocolPresenter createPresenter() {
		return ProtocolPresenter.getInstance();
	}

	@Override protected void initBeforeSetContent() {
		mServiceConfig = new BesServiceConfig();
		mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
		mServiceConfig.setTotaConnect(false);
		mServiceConfig.setUseTotaV2(false);
		mServiceConfig.setServiceUUID(BesSdkConstants.ALIPAY_SERIVICE_UUID);
		mServiceConfig.setCharacteristicsUUID(BesSdkConstants.ALIPAY_CHARACTERISTICRX_UUID);// ALIPAY_CHARACTERISTICRX_UUID
		// mServiceConfig.setCharacteristicsTX(BesSdkConstants.ALIPAY_CHARACTERISTICTX_UUID);
		mServiceConfig.setDescriptorUUID(BES_GATT_DESCRIPTOR_OTA_UUID);
		SPHelper.putPreference(ProtocolActivity.this, BesSdkConstants.BES_SAVE_LOG_NAME, "Protocl");
		mPresenter.setProtocolBBServiceListener(ProtocolActivity.this);
		mPresenter.setProtocolServiceListener(ProtocolActivity.this);
	}

	@Override protected int getContentViewId() {
		return R.layout.act_connect;
	}

	@Override protected void bindView() {
		mContext = getBaseContext();
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		filter.addAction(Constants.ACTION_CONNECT_BLE_DEVICE);
		filter.addAction(Constants.ACTION_DISMISS_LOADING);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
			registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED);
		} else {
			registerReceiver(receiver, filter);
		}
		pick_device_ble = findViewById(R.id.pick_device_ble);
		connect_device = findViewById(R.id.connect_device_connect);
		device_address = findViewById(R.id.device_address_connect);
		device_name = findViewById(R.id.device_name_connect);
		logV = findViewById(R.id.logV);
		done = findViewById(R.id.done);
	}

	@Override protected void initView() {
		getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
		cur_title = getString(R.string.connect_lanxing_device);
		inittoolbar(cur_title);
		pick_device_ble.setOnClickListener(ProtocolActivity.this);
		connect_device.setOnClickListener(ProtocolActivity.this);

		scr_policy = findViewById(R.id.scr_policy);
		loginfo = findViewById(R.id.loginfo);
		tv_title.setOnClickListener(ProtocolActivity.this);
		done.setOnClickListener(ProtocolActivity.this);
		logV.setMovementMethod(ScrollingMovementMethod.getInstance());
		scr_policy.setOnTouchListener((v, event) -> {
			v.getParent().requestDisallowInterceptTouchEvent(true);
			return false;
		});

		// add by wangsm theck the device status from the devicelist fragment
		updateDeviceInfo();
		checkDeviceStatusFromDeviceList();
		// end by wangsm
		registerElpoDataReceiver();
	}

	private void updateDeviceInfo() {
		Intent intent = getIntent();
		if (intent != null) {
			Bundle bundle = intent.getBundleExtra("BUNDLE_CONTENT");
			if (bundle != null) {
				mHmDevice = (HmDevice) bundle.getSerializable("HM_DEVICE");
				mServiceConfig.setDevice(mHmDevice);
				besConnectState = BTService.getDeviceConnectState(this, mServiceConfig);
				Log.d(TAG, "wangsm_bt,besConnectState= " + besConnectState);
				onPickDevice(mHmDevice);
			}
		}
	}

	@Override protected void setInstance() {

	}

	@Override protected void removeInstance() {

	}

	@Override public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_setting_rename, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		if (itemId == android.R.id.home) {
			finish();
			return true;
		} else if (itemId == R.id.menu_item_rename) {
			showRenameDialog();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override public void onClick(View v) {
		if (v.getId() == R.id.pick_device_ble) {
			mPresenter.pickDecice(ProtocolActivity.this, BluetoothConstants.Scan.SCAN_BLE);
		} else if (v.getId() == R.id.connect_device_connect) {
			// bindBleDevice();
			connectBleDevice(true);
		} else if (v.getId() == R.id.done) {
			loginfo.setVisibility(View.GONE);
		} else if (v.getId() == R.id.tv_title) {
			loginfo.setVisibility(View.VISIBLE);
		} else if (v.getId() == R.id.ll_panel) {
			startActivity(new Intent(this, DeviceProfilesActivity.class));
		} else if (v.getId() == R.id.routebook_sync) {
			Log.d(TAG, "begin sync the routebook file to watch");
			Intent intent = new Intent(this, RouteBookDeviceActivity.class);
			intent.putExtra("EXTRA_DEVICE_MODEL", SettingsJsonUtils.getDeviceModel(this));
			intent.putExtra("EXTRA_DEVICE_NAME", SettingsJsonUtils.getSn(this));
			startActivity(intent);
		} else if (v.getId() == R.id.ll_setting) {
			Intent intent = new Intent(this, SettingsActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("HM_DEVICE", mHmDevice);
			// intent.putExtra("DEVICE_NAME",deviceName);
			// intent.putExtra("DEVICE_ADDRESS",deviceAddress);
			intent.putExtra("BUNDLE_CONTENT", bundle);
			intent.putExtra("IS_SETTING", true);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else if (v.getId() == R.id.ll_fireware_update) {
			selfColseService = true;
			BleConnector bleConnector = (BleConnector) mPresenter.getProtocolService().getmDeviceConnector();
			bleConnector.disconnect(mHmDevice);
			Intent otaIntent = new Intent(this, OtaUIActivity.class);
			BesServiceConfig serviceConfig = new BesServiceConfig();
			serviceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
			serviceConfig.setServiceUUID(BesSdkConstants.BES_OTA_SERVICE_OTA_UUID);
			serviceConfig.setCharacteristicsUUID(BesSdkConstants.BES_OTA_CHARACTERISTIC_OTA_UUID);
			serviceConfig.setDescriptorUUID(BesSdkConstants.BES_OTA_DESCRIPTOR_OTA_UUID);
			serviceConfig.setDevice(mHmDevice);
			serviceConfig.setUSER_FLAG(1);
			otaIntent.putExtra(com.besall.allbase.common.Constants.OTA_SERVICE_CONFIG, serviceConfig);
			startActivity(otaIntent);
		} else if (v.getId() == R.id.ll_elpo) {
			showLoading(null);
			syncImageView.startAnimation(syncAnimation);
			//CommonUtil.downloadELPOData(this, mPresenter.getProtocolService());
			File old_file = new File(AppFileUtils.buildExternalDirectoryPath(SettingsJsonUtils.SETTINGS), SettingsJsonUtils.LOCATION_JSON);
			if (old_file.exists()) {
				boolean del = old_file.delete();
			}
			//LatLng earth2Baidu = BiCiCoorConverter.earth2Baidu(SharedManager.getInstance().getCurLatLngWithMP());
			LatLng gpsLocation = SharedManager.getInstance().getCurLatLngWithMP();
			CommonUtil.saveLocationData(gpsLocation, old_file);
			sendIcoeLocationFile();
			// mPresenter.sendIcoeKey();
		} else if (v.getId() == R.id.ll_manual_book) {
			IntentUtils.gotoWebBrowser(this, BesSdkConstants.BES_BLE_SETTING_MANUAL, null);
		} else if (v.getId() == R.id.ll_help) {
			Log.i(TAG, "Help Center no function ");
		} else if (v.getId() == R.id.ll_storage) {
			Intent storageManagerIntent = new Intent(this, StorageManagerActivity.class);
			storageManagerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(storageManagerIntent);
		}
	}

	@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "requestCode:  " + requestCode + "  resultCode: " + resultCode);
		if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_SCAN) {
			if (resultCode == RESULT_OK) {
				mHmDevice = (HmDevice) data.getSerializableExtra(BES_SCAN_RESULT);
				onPickDevice(mHmDevice);
			}
		} else if (requestCode == REQUEST_LOG_FILE) {
			onPickUpFile(resultCode, data);
		} else if (requestCode > OTA_CHOOSE_FILE_PATH_RESULT - 2 && requestCode < OTA_CHOOSE_FILE_PATH_RESULT + 20) {
			onPickFile(resultCode, data, requestCode);
		}
	}

	private void onPickDevice(HmDevice hmDevice) {
		// add by wangsm
		String deviceName = hmDevice.getDeviceName();
		String deviceAddress = hmDevice.getBleAddress();
		Log.i(TAG, "onPickDevice: " + deviceName);
		Log.i(TAG, "onPickDevice: " + deviceAddress);
		Log.i(TAG, "onPickDevice hmDevice: " + hmDevice);
		// end by wangsm
		device_address.setText(deviceAddress);
		mServiceConfig.setDevice(hmDevice);
		if (deviceName != null) {
			SpannableString ss = new SpannableString(deviceName);
			BesSdkConstants.BesConnectState state = BTService.getDeviceConnectState(ProtocolActivity.this, mServiceConfig);
			if (state == BES_CONNECT) {
				ss.setSpan(new ForegroundColorSpan(Color.rgb(103, 200, 77)), 0, deviceName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			device_name.setText(ss);
		}
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {
		Log.i(TAG, "onTotaConnectState: state: " + state);
	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {
		Log.i(TAG, "onErrorMessage: msg: " + msg);
		if (BES_CONNECT_ERROR == msg && !selfColseService) {
			runOnUiThread(() -> {
				dismissLoading();
				showToast(R.string.pls_conn_device);
			});
		}
	}

	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
		Log.i(TAG, "onStateChangedMessage: msgStr: " + msgStr + "msg: " + msg);
		runOnUiThread(() -> {
			if (msg == SYSTEM_TRANS_ELPO_DATA_FILE) {
				Log.i(TAG, "onStateChangedMessage: SYSTEM_TRANS_ELPO_DATA_FILE ,finisih: ");
				Toast.makeText(mContext, msgStr, Toast.LENGTH_SHORT).show();
				requestLeftTime();
			}
			// add by wangsm for connect error msg
			else if (msg == BES_CONNECT_ERROR && !selfColseService) {
				Log.i(TAG, "onStateChangedMessage: not connected ,finish: ");
				Toast.makeText(mContext, msgStr, Toast.LENGTH_SHORT).show();
				finish();
			}
			// end by wangsm
			else if (msg == BES_CONNECT_SUCCESS) {
				// entry the device setting ui //add by wangsm
				dismissLoading();
				SmartDevice smartDevice = convertToSmartDevice();
				if (null == smartDevice) {
					return;
				}
				SharedManager.getInstance().saveCurConnDeviceAddress(smartDevice.getAddress());
				saveNewConnectedDevice(smartDevice);
				initDeviceLayout();
				// add by wangsm
			} else if (msg == BES_CONNECT_ERROR) {
				addToView(msgStr, 2, true);
				// addToView(msgStr,2);//bes origin code
			} else if (msg == RECEIVE_DATA_LOG) {
				addToView(msgStr, 1, true);
				// addToView(msgStr,2);//bes origin code
				// addToView(msgStr, 1);

			} else if (msg == RETURN_SEND_LOG) {
				Log.i(TAG, "run: RETURN_SEND_LOG");
				addToView(msgStr, 0, true);
				// bes origin code
				// addToView(msgStr,0);
			} else if (msg == KEY_TEST_GET_LOG_FILE_NAME) {
				byte[] d = ArrayUtil.toBytes(msgStr);
				String templog = ArrayUtil.toASCII(d);
				Log.i(TAG, "run: KEY_TEST_GET_LOG_FILE_NAME" + templog.length());
				splitDate(d);
			} else if (msg == KEY_TEST_GET_LOG_FILE) {
				Log.i(TAG, "run: log success");
			} else if (msg == GET_DEVICE_SATELLITE_DATA) {
				int timeRemain = Integer.parseInt(msgStr);
				Log.i(TAG, "timeRemain  = " + timeRemain);
				String ret = TimeUtil.convertSeconds(timeRemain);
				String[] data = ret.split(",");
				long hours = Long.parseLong(data[1]);
				long days = Long.parseLong(data[0]);
				String time;
				if (hours == 0 && days == 0) {
					time = getString(R.string.st_satellite_data_expired);
				} else if (hours == 0) {
					time = getString(R.string.satellite_data_hour_expired, hours);
				} else if (days == 0) {
					time = getString(R.string.satellite_data_day_expired, days);
				} else {
					time = getString(R.string.satellite_data_day_hour_expired, days, hours);
				}
				if (null != tv_satellite_expires_in) {
					tv_satellite_expires_in.setText(time);
				}
			}
		});
	}

	// add by wangsm for atuo sync time
	private void sendCmdToSyncTime() {
		Log.d(TAG, "begin send sync time cmd");
		mPresenter.sendInfoData(INFO_Set_Device_Time, null);
	}

	private void configPkgMTU(String flag) {
		Log.d(TAG, "configPkgMTU");
		mPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_SET_BB_PKG_MTU_MAX, flag, "");
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {
		Log.d(TAG, "ProtocolActivity onSuccessMessage, msg: " + msg);
		//同步时间成功后继续请求
		if (APP_SYNC_TIME_SUCCESS == msg) {
			if (mOnlySyncTime) {
				mOnlySyncTime = false;
			} else {
				syncSettings();
			}
		} else if (FIRST_GET_SETTINGS_JSON_FILE_SUCCESS == msg) {
			String fileDirStr = FileUtils.checkExternalDirectoryPathExist(true, DEVICE_MODEL_DEFAULT, DEVICE_SN_DEFAULT, SettingsJsonUtils.SETTINGS, SettingsJsonUtils.SETTING_JSON);
			Log.i(TAG, "the file dir: " + fileDirStr);
			Settings settings = FileUtils.parseFromFile(fileDirStr, Settings.class);
			Log.i(TAG, "settings = " + settings);
			String device_model = settings.getDevice_model();
			//sn = settings.getSn();
			String sn = "test";//暂时是空的,所以临时用这个文件夹 todo 暂时这样
			SettingsJsonUtils.saveDeviceInfo(mContext, device_model, sn);
			String manufacturer = DeviceUtils.getManufacturer();
			if (!TextUtils.isEmpty(manufacturer)) {
				if (!MANUFACTURER_HUAWEI.equalsIgnoreCase(manufacturer)) {
					configPkgMTU("1");
				}else{
					configPkgMTU("0");
				}
			} else {
				requestLeftTime();
			}
		} else if (DEVICE_RENAME_SUCCESS == msg) {
			SmartDevice smartDevice = convertToSmartDevice();
			Device.storeOrReplaceDevice(smartDevice.getType(), smartDevice.getAddress(), mNewDeviceName, smartDevice.getRssi(), smartDevice.getScanRecord(), SmartDevice.PROTOCOL_BLE, false, App.getContext().getUserId());
			runOnUiThread(() -> {
				mCurrentDeviceName = mNewDeviceName;
				mNewDeviceName = "";
				inittoolbar(mCurrentDeviceName);
				dismissLoading();
				ToastUtils.showShort(R.string.setting_success);
			});
		} else if (SET_DEVICE_PKU_SUCCESS == msg) {
			requestLeftTime();
		}
	}

	@Override public void onBBSMessage(int msg, String params) {
		Log.d(TAG, "ProtocolActivity ,onBBSMessage, msg:" + msg + "  params:" + params);
		if (msg == com.bes.sdk.message.Constants.SAVE_WORKOUT_TRK_FILE_SUCCESS) {
			BBWorkoutsManagerFragment.WorkoutFile workoutFile = parseFileToKey(params);
			if (workoutFile != null && workoutFile.getCount() == 2) {
				BesSportProcessor besData = new BesSportProcessor(SmartDevice.TYPE_BES);
				besData.onStartProcess(workoutFile.getWkFileDir(), workoutFile.getTrkFileDir(), (fitName, result) -> {
					// 处理回调数据
					Log.d(TAG, "onBBSuccessMessage, fitName: " + fitName + ", result: " + result);
					updateSyncedWorkoutList(fitName, result);
				});
			}
		}
	}

	/********************************************************
	 update the worklist after sync the database.
	 *********************************************************/
	private void updateSyncedWorkoutList(String filename, int result) {
		if (filename == null || !filename.endsWith(".wk")) {
			Log.d(TAG, "the filename is error,return ");
			return;
		}

		List<bb.lanxing.lib.devices.sgsettingentity.workout.Workout> currWkList = mWorkouts.getWorkoutList();
		if (currWkList == null || currWkList.isEmpty()) {
			Log.d(TAG, "the currWkList is null,return ");
			return;
		}

		String[] fileNamSplit = filename.split("\\.");
		String syncfileName = fileNamSplit[0];
		Log.d(TAG, "syncfileName:  " + syncfileName);

		int index = 0;
		for (index = 0; index < currWkList.size(); index++) {
			bb.lanxing.lib.devices.sgsettingentity.workout.Workout workout = currWkList.get(index);
			String wkfileName = String.valueOf(workout.getTimestampInYHDHMS());
			// Log.d(TAG,"the Workout file name :"+ wkfileName);
			if (syncfileName.equals(wkfileName)) {
				Log.d(TAG, "set new workout filename: " + wkfileName);
				if (result == BesSportProcessor.BES_SYNC_FINISHED || result == BesSportProcessor.BES_SYNC_DUPLICATED) {
					workout.setState(WorkoutState.Synced);
				}
				currWkList.set(index, workout);
				mWorkouts.setWorkoutList(currWkList);
				break;
			}
		}
	}

	private BBWorkoutsManagerFragment.WorkoutFile parseFileToKey(String fileDir) {
		String key;
		String fileType;
		Log.d(TAG, "parseFileToKey ,fileDir: " + fileDir);
		if (fileDir != null && (fileDir.endsWith(".trk") || fileDir.endsWith(".wk"))) {
			String[] fileSplit = fileDir.split("/");
			String fileName = fileSplit[fileSplit.length - 1];
			Log.d(TAG, "fileSplit trk or wk ,fileName:  " + fileName);
			String[] fileNameSplit = fileName.split("\\.");
			key = fileNameSplit[0];
			fileType = fileNameSplit[1];
			Log.d(TAG, "parseFileToKey,the key is: " + key);

			if (!workoutFileHashMap.containsKey(key)) {
				Log.d(TAG, "parseFileToKey,the key does not exist in map,put it into map");
				BBWorkoutsManagerFragment.WorkoutFile workoutFile = new BBWorkoutsManagerFragment.WorkoutFile();
				workoutFile.setKey(key);
				if (fileType.equals(TRK)) {
					workoutFile.setTrkFileDir(fileDir);
				} else if (fileType.equals(WK)) {
					workoutFile.setWkFileDir(fileDir);
				}
				workoutFile.setCount(1);
				workoutFileHashMap.put(key, workoutFile);
			} else {
				Log.d(TAG, "parseFileToKey,the key exist in map,check the count");
				BBWorkoutsManagerFragment.WorkoutFile existWorkoutFile = workoutFileHashMap.get(key);
				int count = existWorkoutFile.getCount();
				if (count == 2) {
					Log.d(TAG, "parseFileToKey,the count is 2,return directly");
					workoutFileHashMap.remove(key);
					return existWorkoutFile;
				}

				if (fileType.equals(TRK)) {
					existWorkoutFile.setTrkFileDir(fileDir);
				} else if (fileType.equals(WK)) {
					existWorkoutFile.setWkFileDir(fileDir);
				}
				if (existWorkoutFile.getWkFileDir() != null && existWorkoutFile.getTrkFileDir() != null) {
					workoutFileHashMap.remove(key);
					existWorkoutFile.setCount(2);
					Log.d(TAG, "parseFileToKey,trk: " + existWorkoutFile.getTrkFileDir() + "wk: " + existWorkoutFile.getWkFileDir());
					return existWorkoutFile;
				}
			}
		}
		Log.d(TAG, "parseFileToKey,return null");
		return null;
	}

	/*
	 * add by wangsm for show Device UI
	 *
	 */
	public void initDeviceLayout() {
		setContentView(R.layout.fragment_bes_device_home_activity);
		inittoolbar(getString(R.string.setting));
		if (null != mHmDevice) {
			String deviceName = mHmDevice.getDeviceName();
			if (!TextUtils.isEmpty(deviceName)) {
				mCurrentDeviceName = deviceName;
				inittoolbar(deviceName);
			}
		}
		storageLL = findViewById(R.id.ll_storage);
		tv_satellite_expires_in = findViewById(R.id.tv_satellite_expires_in);
		mTextViewLog = findViewById(R.id.tv_stop_watch_log);
		storageLL.setOnClickListener(this);
		Switch switchView = findViewById(R.id.switch_auto_sync);
		int checked = -1;
		if (mHmDevice != null) {
			checked = SharedManager.getInstance().getTimeAutoSync(mHmDevice.getBleAddress(), TIME_AUTO_SYNC);
		} else {
			Log.d(TAG, "the device is null: " + checked);
		}

		Log.d(TAG, "initDeviceLayout,the auto sync time state: " + checked);
		switchView.setChecked(checked == TIME_AUTO_SYNC);
		switchView.setOnCheckedChangeListener(ProtocolActivity.this);
		mPanelSettingLayout = findViewById(R.id.ll_panel);
		mPanelSettingLayout.setOnClickListener(this);

		mRoutebookSyncLayout = findViewById(R.id.routebook_sync);
		mRoutebookSyncLayout.setOnClickListener(this);

		firewareUpdateLayoutView = findViewById(R.id.ll_setting);
		firewareUpdateLayoutView.setOnClickListener(this);

		settingsLayoutView = findViewById(R.id.ll_fireware_update);
		settingsLayoutView.setOnClickListener(this);

		elpoLayoutView = findViewById(R.id.ll_elpo);
		elpoLayoutView.setOnClickListener(this);
		helpLayoutView = findViewById(R.id.ll_help);
		helpLayoutView.setOnClickListener(this);
		fileLayoutView = findViewById(R.id.ll_manual_book);
		fileLayoutView.setOnClickListener(this);
		syncImageView = findViewById(R.id.img_sync);
		syncImageView.setImageResource(R.drawable.ic_re_sync_data);
		syncAnimation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		syncAnimation.setRepeatCount(3);
		syncAnimation.setDuration(1000);
		syncAnimation.setInterpolator(new LinearInterpolator());
		syncAnimation.setAnimationListener(new Animation.AnimationListener() {
			public void onAnimationStart(Animation arg0) {
			}

			public void onAnimationRepeat(Animation arg0) {
			}

			public void onAnimationEnd(Animation arg0) {
				syncImageView.clearAnimation();
			}
		});
		setLogView();
		clickTitleEnableLogFunc();
		sendCmdToSyncTime();
	}

	public void backToConnect() {
		setContentView(R.layout.act_connect);
		bindView();
		initView();
	}

	public void addToView(String msgRet, int status) {
		runOnUiThread(() -> {
			if (data_info != null) {
				String msgs = data_info.getText().toString().trim();
				if (status == 0) {
					msgs += "\r\n" + "\r\n" + "SEND: " + msgRet;
					data_info.setText(msgs);
				} else if (status == 1) {
					msgs += "\r\n" + "\r\n" + "RECEIVE: " + msgRet;
					data_info.setText(msgs);
				} else if (status == 2) {
					msgs += "\r\n" + "\r\n" + msgRet;
					data_info.setText(msgs);
				} else if (status == 3) { // Kit@BB
					msgs += "\r\n" + "\r\n" + "RECEIVE String: \r\n" + msgRet;
					data_info.setText(msgs);
				}
			}
		});
	}

	public boolean checkPubkey(byte[] data) {

		Log.i(TAG, "1111111----: " + ArrayUtil.toHex(data));
		if ((data[0] & 0xff) == 0x09 && (data[1] & 0xff) == 0x02) {
			Log.i(TAG, "checkPubkey: " + ArrayUtil.toHex(data));
			byte[] pkglen = new byte[2];
			java.lang.System.arraycopy(data, 2, pkglen, 0, 2);
			int pkgL = ArrayUtil.byte2int(pkglen);
			Log.i(TAG, "checkPubkey: " + pkgL);

			byte[] pkgData = new byte[pkgL - 4];
			java.lang.System.arraycopy(data, 4, pkgData, 0, pkgL - 4);
			recevieMsg = ArrayUtil.toHex(pkgData);
			state = true;
			return state;
		} else if (data[0] == 0x7f) {
			// 第一包
			if ((data[8] & 0xff) == 0x09 && (data[9] & 0xff) == 0x02) {
				totalCount[0] = data[4];
				totalCount[1] = data[5];
				dataLen[0] = data[10];
				dataLen[1] = data[11];
				totalCounts = ArrayUtil.byte2int(totalCount);// 总包数
				totalLen = ArrayUtil.byte2int(dataLen);// 数据总长度
				Log.i(TAG, "totalCounts: " + totalCounts);
				Log.i(TAG, "totalLen: " + totalLen);
				mpkgData = new byte[170];
				java.lang.System.arraycopy(data, 12, mpkgData, 0, 170);
				tempData = tempData + ArrayUtil.toHex(mpkgData);
				Log.i(TAG, "tempData: 170-------" + tempData);
				time++;
			} else if (time < (totalCounts - 1) && time > 0) {
				mpkgData = new byte[178];
				java.lang.System.arraycopy(data, 4, mpkgData, 0, 178);
				tempData = tempData + ArrayUtil.toHex(mpkgData);
				Log.i(TAG, "tempData: 178----" + tempData);
				time++;
			} else if (time == totalCounts - 1) {
				mpkgData = new byte[totalLen - 170 - 178 * (totalCounts - 2)];
				java.lang.System.arraycopy(data, 4, mpkgData, 0, totalLen - 170 - 178 * (totalCounts - 2));
				tempData = tempData + ArrayUtil.toHex(mpkgData);
				Log.i(TAG, "tempData: last---" + tempData);
				recevieMsg = tempData;
				Log.i(TAG, "checkPubkey: times" + recevieMsg);
				state = true;
				return state;
			}
			Log.i(TAG, "times: " + time);
		}
		Log.i(TAG, "checkPubkeystate: " + state);
		Log.i(TAG, "checkPubkeystate: " + recevieMsg);
		return state;
	}

	public void splitDate(byte[] data) {
		Log.i(TAG, "splitDate: " + ArrayUtil.toHex(data));
		byte[] totalLen = new byte[] { data[0], data[1] };
		int totalLenth = ArrayUtil.byte2int(totalLen);
		int fileCounts = data[3];
		Log.i(TAG, "run: --------" + totalLenth + "   " + fileCounts);
		byte[] trueData = new byte[totalLenth - 2];
		java.lang.System.arraycopy(data, 4, trueData, 0, totalLenth - 2);
		Log.i(TAG, "DATA: " + ArrayUtil.toHex(trueData));

		for (int i = 0; i < fileCounts; i++) {
			curLen = trueData[reminLen];
			byte[] single = new byte[curLen - 1];
			java.lang.System.arraycopy(trueData, reminLen + 1, single, 0, curLen - 1);
			String s = ArrayUtil.toASCII(single);
			reminLen = reminLen + curLen + 1;
			fileNameList.add(i, s);
			// Log.i(TAG, "splitDate: "+ s + i + reminLen);
		}
		// Log.i(TAG, "fileNameList: "+ fileNameList.toString());
		reminLen = 0;
	}

	private void onPickUpFile(int result, Intent data) {
		if (result == RESULT_OK) {
			int id = data.getIntExtra(LOG_FILE_RESULT, 0);
			Log.i(TAG, "file id : " + fileNameList.get(id));
			String file = fileNameList.get(id);
			Log.i(TAG, "onPickUpFile: " + file);
			byte[] params = ArrayUtil.toBytes(ArrayUtil.str2HexStr(file));
			byte[] ret = new byte[params.length + 1];
			java.lang.System.arraycopy(params, 0, ret, 0, params.length);
			Log.i(TAG, "onPickUpFile: " + ArrayUtil.toHex(ret));
			mPresenter.sendDeveloperData(TEST_REQUEST_LOG_BY_FILE_NAME, ret);
		}
	}

	private void chooseFile() {
		FileUtils.fileToHex(ProtocolActivity.this, OTA_CHOOSE_FILE_PATH_RESULT - 1);
	}

	private void onPickFile(int resultCode, Intent data, int requestCode) {

		if (resultCode == RESULT_OK) {
			String filePath;
			filePath = data.getStringExtra(BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE);// wangsm get watch panel file

			if (filePath == null) {
				Log.i(TAG, "onPickFile: the filepath is null, return ");
				return;
			}
			Log.i(TAG, "onPickFile: " + filePath);
			byte[] path = ArrayUtil.toBytes(ArrayUtil.str2HexStr(filePath));

			runOnUiThread(() -> mPresenter.sendDeveloperData(TEST_WATCH_DIAL_OTA, path));
		}
	}

	@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		int id = buttonView.getId();
		if (R.id.switch_auto_sync == id) {
			if (isChecked) {
				if (mHmDevice != null) {
					Log.d(TAG, "set sync time true");
					SharedManager.getInstance().setTimeAutoSync(mHmDevice.getBleAddress(), TIME_AUTO_SYNC);
					mOnlySyncTime = true;
					sendCmdToSyncTime();
				}
			} else {
				if (mHmDevice != null) {
					Log.d(TAG, "set sync time false");
					SharedManager.getInstance().setTimeAutoSync(mHmDevice.getBleAddress(), TIME_UN_AUTO_SYNC);
				}
			}
		}
	}

	/* add by wangsm for btGatt call back to ui */
	public void addToView(String msgRet, int status, boolean isBB) {
		// Log.d(TAG,"wangsm_bes, add to view , use bb code: isBB: "+ isBB);
		if (isBB) {
			getDataShowUi(msgRet, status);
		} else {
			addToView(msgRet, status);
		}
	}

	public void getDataShowUi(String msgRet, int status) {
		runOnUiThread(() -> {
			String msgs = null;
			if (status == 0) {
				msgs = "SEND: " + msgRet;
				Log.d(TAG, "wangsm_bes, getDataShowUi: msg: " + msgs);
			} else if (status == 1) {
				msgs = "RECEIVE: " + msgRet;
				Log.d(TAG, "wangsm_bes, getDataShowUi: msg: " + msgs);

				// syncWorkRequests();
				// testReadJsonFile();
			} else if (status == 2) {
				msgs = msgRet;
				Log.d(TAG, "wangsm_bes, getDataShowUi: msg: " + msgs);
			}
		});
	}

	// add by bb
	public boolean writeJsonStrToFile(String jsonString, String filePath) {
		boolean result = false;
		File file = new File(filePath);
		result = writeJsonStrToFile(jsonString, file);
		return result;
	}

	public boolean writeJsonStrToFile(String jsonString, File jsonFile) {

		FileOutputStream fileOutputStream = null;

		if (jsonString == null || jsonFile == null || jsonFile.isDirectory()) {
			Log.d(TAG, "wangsm_bes, writeJsonStrToFile,file is error,return  ");
			return false;
		}

		if (jsonFile.exists()) {
			jsonFile.delete();
		} else {
			try {
				boolean result = jsonFile.createNewFile();
				if (!result) {
					Log.d(TAG, "wangsm_bes, writeJsonStrToFile create file fail, the file is: " + jsonFile.getAbsolutePath());
					return false;
				}
				fileOutputStream = new FileOutputStream(jsonFile, true);
				fileOutputStream.write(jsonString.getBytes(Charset.forName("UTF-8")));
				fileOutputStream.flush();

				Log.d(TAG, "wangsm_bes, writeJsonStrToFile,file write success ,path: " + jsonFile.getAbsolutePath());
			} catch (IOException e) {
				throw new RuntimeException(e);
			} finally {
				if (fileOutputStream != null) {
					try {
						fileOutputStream.close();
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				}
			}
		}

		return true;
	}

	/* param file: is the target file */
	public String readTextFromFile(File file) {
		String jsonStr = null;
		char cbuf[] = new char[buffSize];

		if (file == null || !file.exists() || !file.isFile()) {
			Log.d(TAG, "wangsm_bes, readTextFromFile,file is error,return  ");
			return null;
		}

		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, Charset.forName("UTF-8"));
			StringBuffer sb = new StringBuffer();
			int num = inputStreamReader.read(cbuf, 0, buffSize);
			while (num >= 0) {
				sb.append(cbuf, 0, num);
				num = inputStreamReader.read(cbuf, 0, buffSize);
			}
			jsonStr = sb.toString();
			Log.d(TAG, "wangsm_bes, the json str  is: " + jsonStr);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return jsonStr;
	}

	public void testWriteJsonStrToFile(String jsonStr) {
		File files = getExternalFilesDir(null);
		String jsonFileDir = files.getAbsolutePath() + File.separator + "peripheral.devices" + File.separator + "A1" + File.separator + "795401" + File.separator + "Ephemeris" + File.separator + "workoutsbk.json";
		writeJsonStrToFile(jsonStr, jsonFileDir);
	}

	// add by wangsm
	public SmartDevice convertToSmartDevice() {// BluetoothDevice mDevice
		if (mHmDevice == null) {
			Log.d(TAG, "wangsm_bes,convertToSmartDevice fail,the device is null");
			return null;
		}
		DeviceProvider deviceProvider = DeviceHelper.getDeviceProvider();
		if (null == deviceProvider) {
			Log.e(TAG, "wangsm_bes,convertToSmartDevice fail,the deviceProvider is null");
			return null;
		}
		SmartDevice deviceByAddress = deviceProvider.getDeviceByAddress(mHmDevice.getBleAddress());
		if (deviceByAddress == null) {
			deviceByAddress = DeviceHelper.getDeviceProvider().create();
		}
		deviceByAddress.setName(mHmDevice.getDeviceName());
		deviceByAddress.setAddress(mHmDevice.getBleAddress());
		deviceByAddress.setRssi(mHmDevice.getRssi());// this.rssi
		// deviceByAddress.setScanRecord(this.scanRecord);
		deviceByAddress.setType(SmartDevice.TYPE_BES);
		deviceByAddress.setProtocol(SmartDevice.PROTOCOL_BLE);
		return deviceByAddress;
	}

	private void saveNewConnectedDevice(SmartDevice smartDevice) {

		if (smartDevice == null) {
			Log.d(TAG, "the smart device is null,return");
			return;
		}

		Device device = Device.getByAddress(smartDevice.getAddress(), App.getContext().getUserId());
		if (device == null || (!device.getName().equals(smartDevice.getName()) && (device.getAddress().equals(smartDevice.getAddress())))) {
			// val needAutoConnectTypes = Device.getNeedAutoConnectTypes()

			// if (needAutoConnectTypes.contains(device.type)) {
			Device.storeOrReplaceDevice(smartDevice.getType(), smartDevice.getAddress(), smartDevice.getName(), smartDevice.getRssi(), smartDevice.getScanRecord(), SmartDevice.PROTOCOL_BLE, false, App.getContext().getUserId());
			// }
			AbstractXZDeviceManager deviceManager = (AbstractXZDeviceManager) XZDeviceHelper.getDeviceManager();
			if (deviceManager != null) {
				Log.d(TAG, "create device if need");
				deviceManager.createDeviceIfNeed(smartDevice);
			} else {
				Log.d(TAG, "deviceManager is null");
			}
		}
	}

	private void bindBleDevice() {
		BluetoothManager btManager = BtHeleper.getBluetoothManager(mContext);
		BluetoothAdapter btAdapter = btManager.getAdapter();
		btDevice = btAdapter.getRemoteDevice(mHmDevice.getBleAddress());
		/* try { */

		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
			// TODO: Consider calling
			// ActivityCompat#requestPermissions
			// here to request the missing permissions, and then overriding
			// public void onRequestPermissionsResult(int requestCode, String[] permissions,
			// int[] grantResults)
			// to handle the case where the user grants the permission. See the documentation
			// for ActivityCompat#requestPermissions for more details.
			Log.d(TAG, "no connect permission.");
			return;
		}
		btDevice.createBond();
		/*
		 * BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord(ALIPAY_SERIVICE_UUID);
		 * btSocket.connect();
		 */
		/*
		 * } catch (IOException e) { throw new RuntimeException(e); }
		 */
	}

	public void connectBleDevice(boolean needShowLoading) {
		ProtocolService service = mPresenter.getProtocolService();
		if (null != service) {
			ArrayList<HmDevice> curConBleDevices = BleConnector.getsConnector(ProtocolActivity.this, null, null).getCurConnectDevices();
			if (curConBleDevices != null && !curConBleDevices.isEmpty()) {
				Log.d(TAG, "the curConBleDevices size: " + curConBleDevices.size());
				HmDevice hmDevice = curConBleDevices.get(0);
				String address = hmDevice.getBleAddress();
				Log.d(TAG, "the address: " + address);
				if (mHmDevice != null && !address.equals(mHmDevice.getBleAddress())) {
					showToast(R.string.pls_unbind_device);
					return;
				}
			}
			BleConnector bleConnector = BleConnector.getsConnector(this, null, null);
			if (mHmDevice == null) {
				showToast(R.string.pleaseSelectDevice);
				return;
			} else {
				bleConnector.disconnect(mHmDevice);
			}
			// Log.d(TAG,"the bleConnector: "+ bleConnector);
			// if(bleConnector != null){
			// ArrayList<HmDevice> arrayList = bleConnector.getCurConnectDevices();
			// }
		}
		if (mHmDevice == null) {
			showToast(R.string.pleaseSelectDevice);
			return;
		}
		if (needShowLoading) {
			showLoading(null);
		}
		selfColseService = false;
		mServiceConfig.setDevice(mHmDevice);
		mPresenter.connectDevice(mServiceConfig, ProtocolActivity.this, ProtocolActivity.this);
	}

	// for test
	private void showLoading(DialogInterface.OnCancelListener onCancelListener) {
		if (circularProgressDialog == null) {
			circularProgressDialog = new CircularProgressDialog(this, true, false, onCancelListener);
		}
		circularProgressDialog.show(R.string.dialog_loading);
	}

	public void dismissLoading() {
		if (circularProgressDialog != null) {
			circularProgressDialog.dismiss();
			circularProgressDialog = null;
		}
	}

	private void checkDeviceStatusFromDeviceList() {
		BluetoothManager btManager = BtHeleper.getBluetoothManager(mContext);
		BluetoothAdapter btAdapter = btManager.getAdapter();
		if (btAdapter == null) {
			showToast(R.string.device_bluetooth_not_supported);
			finish();
			return;
		}
		if (!btAdapter.isEnabled()) {
			showToast(R.string.pls_open_bt);
			finish();
			return;
		}

		int isFromList = getIntent().getIntExtra("is_from_devicelist", 0);
		Log.d(TAG, "wangsm_bt,besConnectState= " + besConnectState);
		if (isFromList == 1 && besConnectState != BesSdkConstants.BesConnectState.BES_CONNECT) {
			showToast(R.string.pls_conn_device);
			Log.d(TAG, "wangsm_bes, checkDeviceStatusFromDeviceList, pls connect device: ");
			// connectBleDevice();//showToast(R.string.pls_conn_device);
		} else if (besConnectState != BesSdkConstants.BesConnectState.BES_CONNECT) {
			Log.d(TAG, "wangsm_bes, checkDeviceStatusFromDeviceList,connect device: ");
			connectBleDevice(true);
		} else {
			Log.d(TAG, "wangsm_bes, checkDeviceStatusFromDeviceList, init device layout");
			initDeviceLayout();
		}
	}

	/**
	 * q
	 */
	private void requestLeftTime() {
		mPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_GET_ICOE_DATA_LEFT_TIME, "", "");
	}

	private void requestMacAddress() {
		mPresenter.sendInfoData(INFO_Get_mac_address, null);
	}

	private void registerElpoDataReceiver() {
		if (mElpoDataReceiver == null) {
			mElpoDataReceiver = new BroadcastReceiver() {
				@Override public void onReceive(Context context, Intent intent) {
					String extraURL = intent.getStringExtra(DownloadService.EXTRA_DOWNLOAD_URL);
					String extraPath = intent.getStringExtra(DownloadService.EXTRA_OUTPUT_PATH);
					Log.i(TAG, "onReceive URL: " + extraURL);
					Log.i(TAG, "onReceive PATH: " + extraPath);
					runOnUiThread(() -> {
						if (extraURL.contains("f1e1G3.pgl")) {
							elpoFileList.add(extraPath);
						}
						// if (extraURL.contains("ELPO_GAL_3.DAT")) {
						if (extraURL.contains("f1e1E3.pgl")) {
							elpoFileList.add(extraPath);
						}
						// if (extraURL.contains("ELPO_BDS_3.DAT")) {
						if (extraURL.contains("f1e1C3.pgl")) {
							elpoFileList.add(extraPath);
							mPresenter.sendBikeWatchRouteBooksFiles(ProtocolActivity.this, elpoFileList);
							if (elpoFileList != null) {
								elpoFileList.clear();
							}
						}
					});
				}
			};
		}
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
			registerReceiver(mElpoDataReceiver, new IntentFilter(DownloadService.ACTION_DOWNLOAD_COMPLETED), Context.RECEIVER_EXPORTED);
		} else {
			registerReceiver(mElpoDataReceiver, new IntentFilter(DownloadService.ACTION_DOWNLOAD_COMPLETED));
		}
	}

	private void sendIcoeLocationFile() {
		String extraPath = CommonUtil.locationPath;
		Log.i(TAG, "sendIcoeLocationFile PATH: " + extraPath);
		String fileName = extraPath.substring(extraPath.lastIndexOf(File.separatorChar) + 1);
		Log.i(TAG, "fileName: " + fileName);
		byte[] pathElpo = ArrayUtil.toBytes(ArrayUtil.str2HexStr(extraPath));
		if (extraPath.contains(SettingsJsonUtils.LOCATION_JSON)) {
			SPHelper.putPreference(this, KEY_LOCATION_FILE_ID, fileName);
			mPresenter.sendDeveloperData(SYSTEM_TRANS_LOCATION_FILE, pathElpo);
		}
	}

	@Override public void onCancel(DialogInterface dialog) {
		if (circularProgressDialog != null) {
			circularProgressDialog.dismiss();
			circularProgressDialog = null;
		}
		if (mPresenter != null) {
			Log.d(TAG, "loading dialog on cancel,send give up trans file cmd");
			mPresenter.giveUpTransFiles(this);
		}
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	/**
	 * 连续点击6次,显示码表log传输功能
	 */
	private void clickTitleEnableLogFunc() {
		final int max = 6;
		final long intervalTime = 300L;

		resetClickCount();
		setIntervalTime(intervalTime);
		setClickCountTotal(max);
		if (null != tv_title) {
			tv_title.setOnClickListener(v -> {
				boolean isOpen = (boolean) PreferenceUtil.get(ProtocolActivity.this, KEY_STOP_WATCH_LOG, false);
				if (!isOpen) {
					if (0 != startTime) {
						long currentTime = java.lang.System.currentTimeMillis();
						long time = currentTime - startTime;
						if (time > 60000L) {
							clickCount = 0;
						}
					}
					Log.i(TAG, "clickCount = " + clickCount);
					if (0 == clickCount) {
						clickCount++;
						startTime = java.lang.System.currentTimeMillis();
					} else if (getClickCountTotal() != clickCount) {
						long currentTime = java.lang.System.currentTimeMillis();
						if (currentTime - startTime > getIntervalTime()) {
							clickCount = 1;
						} else {
							clickCount++;
						}
						startTime = java.lang.System.currentTimeMillis();
					} else {
						clickCount = 0;
						startTime = 0;
						ToastUtils.showShort(R.string.setting_stop_watch_log_tips);
						PreferenceUtil.put(ProtocolActivity.this, KEY_STOP_WATCH_LOG, true);
					}
				} else {
					ToastUtils.showShort(R.string.setting_stop_watch_log_tips);
					setLogView();
				}
			});
		}
	}

	private void setLogView() {
		if (null != mTextViewLog) {
			boolean isOpen = (boolean) PreferenceUtil.get(ProtocolActivity.this, KEY_STOP_WATCH_LOG, false);
			if (isOpen) {
				mTextViewLog.setVisibility(View.VISIBLE);
				mTextViewLog.setOnClickListener(v -> {
					Intent intent = new Intent(this, StopWatchLogActivity.class);
					startActivity(intent);
				});
			} else {
				mTextViewLog.setVisibility(View.GONE);
			}
		}
	}

	@Override protected void onResume() {
		super.onResume();
		setLogView();
	}

	private void syncSettings() {
		Log.d(TAG, "ProtocolActivity syncSettings");
		MsgStrAnalyzer.setMsgCallBackId(FIRST_GET_SETTINGS_JSON_FILE_SUCCESS);
		mPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_get_settings_info, "", "");
	}

	private void showRenameDialog() {
		new CommonDialogFragment(R.layout.dialog_setting_devicd_rename, (root, dialogFragment) -> {
			Button negativeBtn = root.findViewById(R.id.negativeBtn);
			Button positiveBtn = root.findViewById(R.id.positiveBtn);
			EditText editText = root.findViewById(R.id.wdt_content);
			negativeBtn.setOnClickListener(view -> dialogFragment.dismissAllowingStateLoss());
			positiveBtn.setOnClickListener(view -> {
				dialogFragment.dismissAllowingStateLoss();
				String result = editText.getText().toString();
				if (!TextUtils.isEmpty(result)) {
					if (!result.equals(mCurrentDeviceName)) {
						renameDeviceName(result);
					}
				}
			});
		}).setMargin(ConvertUtils.dp2px(10f)).show(getSupportFragmentManager());
	}

	private void renameDeviceName(String newName) {
		showLoading(null);
		mNewDeviceName = newName;
		mPresenter.sendInfoData(INFO_Set_serial_number, ByteUtils.stringToBytes(newName));
	}
}
